const router = require("koa-router")();
const url = require("url");
const ueditor = require("koa2-ueditor");

let manage = require("./admin/manage");
let login = require("./admin/login");
let index = require("./admin/index");
let articalcate = require("./admin/articalcate");
let article = require("./admin/article");
let focus = require("./admin/focus.js");
let link = require("./admin/link.js");
let nav = require("./admin/nav.js");
let setting = require("./admin/setting.js");
/* 配置路由中间件--获取url地址--配合静态资源的访问 */
router.use(async (ctx, next) => {
  //模板引擎配置全局的变量
  ctx.state.__HOST__ = "http://" + ctx.request.header.host; // localhost:3000
  let pathname = url.parse(ctx.request.url).pathname.substring(1); // admin
  let splitPathname = pathname.split("/"); //分割的目的是拿到路由地址后判断左侧tab切换后是否高亮  ['admin']
  console.log(pathname, splitPathname, ctx.request.header.host);
  //配置全局的对象，方便在多个地方使用，在首页显示当前登陆成员
  ctx.state.G = {
    manageInfo: ctx.session.userInfo,
    url: splitPathname,
    prevPage: ctx.request.headers["referer"],
  };
  //权限设置
  if (ctx.session.userInfo) {
    await next();
  } else {
    //没有登陆跳转到登陆
    if (
      pathname == "admin/login" ||
      pathname == "admin/login/doLogin" ||
      pathname == "admin/login/code"
    ) {
      await next();
    } else {
      ctx.redirect("/admin/login");
    }
  }
});

/* 路由以及子路由的配置 */
//后台管理系统首页
router.use(index);
//管理员界面
router.use("/manage", manage);
//用户登录界面
router.use("/login", login);
//文章分类信息列表
router.use("/articalcate", articalcate);
//文章信息列表
router.use("/article", article);
// 轮播图
router.use("/focus", focus);
// 友情链接
router.use("/link", link);
// 导航
router.use("/nav", nav);
// 系统设置
router.use("/setting", setting);
//注意上传图片的路由   ueditor.config.js配置图片post的地址
router.all(
  "/editor/controller",
  ueditor([
    "public",
    {
      imageAllowFiles: [".png", ".jpg", ".jpeg"],
      imagePathFormat: "/upload/ueditor/image/{yyyy}{mm}{dd}/{filename}",
    },
  ])
);
module.exports = router.routes();
